<template>
   <div class="hello">
    <div id="cesiumContainer" style="position: relative;">
        <div class="drew">
            <el-tooltip content="点"  placement="bottom" popper-class="testtooltip">
                <el-tag @click="drewPoint(1)" :type="index==1 ? '' : 'info'" :effect="index===1 ?'dark':'plain'">
                    <!-- <span class="iconfont icon-yuan"></span> -->
                    <svg class="icon" aria-hidden="true" style="font-size:16px">
                       <use xlink:href="#icon-Point"></use>
                    </svg>
                </el-tag>
            </el-tooltip>   
            <el-tooltip content="线"  placement="bottom" popper-class="testtooltip ">
                <el-tag @click="drewLine(2)" :type="index==2 ? '' : 'info'" :effect="index===2 ?'dark':'plain'">
                    <span class="iconfont icon-xian"></span>
                </el-tag>
            </el-tooltip>        
            <el-tooltip content="面"  placement="bottom" popper-class="testtooltip ">
                <el-tag @click="drewPolygon(4)" :type="index==4 ? '' : 'info'" :effect="index===4 ?'dark':'plain'">
                    <span class="iconfont icon-mian"></span>
                </el-tag>
            </el-tooltip>        
            <el-tooltip content="清除"  placement="bottom" popper-class="testtooltip ">
                <el-tag @click="removeInputAction(7)" :type="dIndex==7 ? '' : 'info'" :effect="dIndex===7 ?'dark':'plain'">
                    <span class="iconfont icon-delete" style="color:#F71F19"></span>
                </el-tag> 
            </el-tooltip>              
        
        </div>
    </div>
  </div>
</template>

<script>
export default{
    name:'CesiumDraw',
    data(){
        return{
            viewer:{},
            inter:null,
            index:-1,
            dIndex:0,
            handler:null,
        }
    },
    mounted() {
        /**
         *初始化cesium
         */
        
        this.initCesium(); 
    },
    methods:{
        /**
         * 
         * 初始化cesium
         * 
         */
        initCesium(){
            Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxOThkNmNmNS1jMjYxLTQzNDMtYjFiOC1kYTU2MGZmYzNhZjUiLCJpZCI6Njg3MjYsImlhdCI6MTY0MDIyNzMzOH0.Hq7YWBI3wJUCtpJfmrb_kQ8dtN5hn-M3km-NG_SsPiQ';
            this.viewer = new Cesium.Viewer('cesiumContainer',{      
                geocoder:false,
                homeButton:false,
                sceneModePicker:false,
                baseLayerPicker:false,
                selectionIndicator: false,
                navigationHelpButton :false,//导航帮助按钮，显示默认的地图控制帮助
                animation:false,// 动画器件，控制视图动画的播放速度.
                timeline:false,//时间线,指示当前时间，并允许用户跳到特定的时间
                creditsDisplay:false,//版权显示，显示数据归属，必选
                infoBox: false,
                fullscreenButton:false,//关闭全屏按钮
                // 注释时相当于使用默认地形，解开注释相当于使用全球地形
                terrainProvider: Cesium.createWorldTerrain({
                    //基于太阳位置开启地形照明
                    requestVertexNormals: true,
                    //启用水体效果
                    requestWaterMask: true
                })
            });
            // 隐藏版权信息
            this.viewer._cesiumWidget._creditContainer.style.display = "none";    // 隐藏版权信息
            this.viewer.scene.skyAtmosphere.show=true;    // 隐藏大气层,false, true开启
            this.viewer.scene.globe.enableLighting = true; //开启光照效果


            let that = this;
            this.viewer.scene.globe.enableLighting = true
            this.viewer.shadows = true
            this.viewer.terrainShadows = Cesium.ShadowMode.RECEIVE_ONLY
            this.viewer.shadowMap.darkness = 0.02 //阴影透明度--越大越透明
            let time = 0
    
            this.inter = setInterval(() => {
                // 改变时间设置光照效果
                let date = new Date().getTime() + time
                let utc = Cesium.JulianDate.fromDate(new Date(date))
                //北京时间
                that.viewer.clockViewModel.currentTime = Cesium.JulianDate.addHours(utc, 0, new Cesium.JulianDate())
                time = time + 1000 * 60
            }, 100)
            console.log(this.inter)

            //解决viewer.scene.pickPosition(e.position)在没有3dTile模型下的笛卡尔座标不准问题。
            that.viewer.scene.globe.depthTestAgainstTerrain = true;

            that.viewer.scene.camera.setView({
                destination:new Cesium.Cartesian3.fromDegrees(112.405419,23.073514,20000),
                orientation: {
                    heading:  0.0, //当前的方向，正北。方位角，北偏东的角度
                    pitch:  Cesium.Math.toRadians(-60),//垂直视线方向和水平面的夹角,Pitch为正 表示方向向量指向水平平面上方，反之表示方向向量指向平面下方，正值从下往上看
                    roll:  0.0 //平面的旋转角度。是方向向量以正东方向为轴的旋转角度,40.0向上翻
                }
            })
        },
        /**
         * 
         * 绘制point
         * 
         */
        drewPoint(key){
            let that = this;
            that.index = key;
            that.removeInputAction(0)
            that.handler= new Cesium.ScreenSpaceEventHandler(that.viewer.scene.canvas)
            that.handler.setInputAction(e => {                
                let position = that.viewer.scene.pickPosition(e.position);
                that.viewer.entities.add({
                    position : position,
                    point : {
                        color: Cesium.Color.SKYBLUE,
                        pixelSize: 10,
                        outlineColor: Cesium.Color.YELLOW,
                        outlineWidth: 3,
                        disableDepthTestDistance: Number.POSITIVE_INFINITY
                    }
                });
                console.log(e)
            },Cesium.ScreenSpaceEventType.LEFT_CLICK)
        },
        /**
         * 
         * 绘制line
         * 
         */
        drewLine(key){
            let that = this
            that.index = key
            let  positions = []
            let tempPositions = []
            that.removeInputAction(0)
            //创建一个屏幕控制实例
            that.handler= new Cesium.ScreenSpaceEventHandler(that.viewer.scene.canvas)
            that.handler.setInputAction( e =>{
                let position = that.viewer.scene.pickPosition(e.position);
                if (!position) {
                    const ellipsoid = that.viewer.scene.globe.ellipsoid;
                    position = that.viewer.scene.camera.pickEllipsoid(e.position, ellipsoid);
                }
                if (!position) return;
                positions.push(position);
                console.log(positions)
                if(positions.length == 1){
                    that.viewer.entities.add({
                        position : positions[0],
                        type: "MeasureDistanceVertex",
                        billboard: {
                            image: require('@/assets/iconImage/start.png'),
                            // 设置颜色和透明度
                            color: Cesium.Color.WHITE.withAlpha(0.8),
                            // 高度（以像素为单位）
                            height: 130,
                            // 宽度（以像素为单位）
                            width: 100,
                            // 逆时针旋转
                            // rotation: 20,
                            // 大小是否以米为单位
                            sizeInMeters: false,
                            // 相对于坐标的垂直位置
                            // verticalOrigin: Cesium.VerticalOrigin.CENTER,
                            // 相对于坐标的水平位置
                            // horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                            // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
                            // pixelOffset: new Cesium.Cartesian2(10, 0),
                            // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
                            scale: 1.0,
                            // 是否显示
                            show: true,
                            disableDepthTestDistance: Number.POSITIVE_INFINITY,//去掉地形遮挡
                            scaleByDistance: new Cesium.NearFarScalar(300, 1, 1200, 0.4), //设置随图缩放距离和比例
                            // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000), //设置可见距离 10000米可见
                            // verticalOrigin: Cesium.VerticalOrigin.BOTTOM
                        },
                        point: {
                            color: Cesium.Color.FUCHSIA,
                            pixelSize: 6,
                        },
                    });
                    createLineEntity()
                    return ;
                }
                createVertex()
                console.log(e)
            },Cesium.ScreenSpaceEventType.LEFT_CLICK)

            that.handler.setInputAction( e => {
                let position = that.viewer.scene.pickPosition(e.endPosition);
                if (!position) {
                    position = that.viewer.scene.camera.pickEllipsoid(e.startPosition, that.viewer.scene.globe.ellipsoid);
                }
                if (!position) return;
                if(positions.length < 1) return;
                tempPositions = positions.concat(position)
                console.log(e)
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

            that.handler.setInputAction( e => {
                debugger
                let position =that.viewer.scene.pickPosition(e.position);
                if (!position) {
                    const ellipsoid = that.viewer.scene.globe.ellipsoid;
                    position = that.viewer.scene.camera.pickEllipsoid(e.position, ellipsoid);
                }
                if (!position) return;
                positions.push(position)
                // createVertex()
                that.viewer.entities.add({
                    position : positions[positions.length - 1],
                    type: "MeasureDistanceVertex",
                    billboard: {
                        image: require('@/assets/iconImage/end.png'),
                        // 设置颜色和透明度
                        color: Cesium.Color.WHITE.withAlpha(0.8),
                        // 高度（以像素为单位）
                        height: 130,
                        // 宽度（以像素为单位）
                        width: 100,
                        // 大小是否以米为单位
                        sizeInMeters: false,
                        // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
                        scale: 1.0,
                        // 是否显示
                        show: true,
                        disableDepthTestDistance: Number.POSITIVE_INFINITY,
                        scaleByDistance: new Cesium.NearFarScalar(300, 1, 1200, 0.4), //设置随图缩放距离和比例
                        // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000), //设置可见距离 10000米可见
                        // verticalOrigin: Cesium.VerticalOrigin.BOTTOM
                    },
                    point: {
                        color: Cesium.Color.FUCHSIA,
                        pixelSize: 6,
                    },
                });
                that.handler.destroy();//关闭事件句柄
                that.handler = null;
                console.log(e)
            }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

            //创建线对象
            function  createLineEntity() {
                that.viewer.entities.add({
                    polyline: {
                        positions: new Cesium.CallbackProperty(e => {
                            return tempPositions;
                        }, false),
                        width: 2,
                        material:  Cesium.Color.BLUE,
                        depthFailMaterial:  Cesium.Color.BLUE,
                        clampToGround: true,//贴地画线
                    }
                })
            }
            //创建线节点
            function  createVertex() {
                that.viewer.entities.add({
                    position: positions[positions.length - 1],
                    id: "MeasureDistanceVertex" + positions[positions.length - 1],
                    type: "MeasureDistanceVertex",
                    point: {
                        color: Cesium.Color.FUCHSIA,
                        pixelSize: 8,
                        scaleByDistance: new Cesium.NearFarScalar(1500, 1, 20000, 0.3),//
                        translucencyByDistance: new Cesium.NearFarScalar(1500, 1, 20000, 0.2),
                        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 20000)
                    },
                });
            }

        },
        /**
         * 
         * 绘制面
         * 
         */
        drewPolygon(key){
            let that = this
            that.index = key;
            that.removeInputAction(0)
            // let height = undefined
            let  positions = []
            let polygonPositions = []

            that.handler= new Cesium.ScreenSpaceEventHandler(that.viewer.scene.canvas)
            that.handler.setInputAction( e =>{
                let position = that.viewer.scene.pickPosition(e.position);
                if (!position) {
                    const ellipsoid = that.viewer.scene.globe.ellipsoid;
                    position = that.viewer.scene.camera.pickEllipsoid(e.position, ellipsoid);
                }
                if (!position) return;
                positions.push(position);
                if( positions.length == 1 ) {
                    createSatrtPointEntity()
                    createPolygonEntity()
                    return ;
                }
                createVertex()

            },Cesium.ScreenSpaceEventType.LEFT_CLICK)


            that.handler.setInputAction( e=>{
                let position = that.viewer.scene.pickPosition(e.endPosition);
                if (!position) {
                    position = that.viewer.scene.camera.pickEllipsoid(e.startPosition, that.viewer.scene.globe.ellipsoid);
                }
                if (!position) return;
                handleMoveEvent(position)
            },Cesium.ScreenSpaceEventType.MOUSE_MOVE)

            that.handler.setInputAction( e=>{
                createEndPointEntity()
                that.handler.destroy();//关闭事件句柄
                that.handler = null;
                console.log(e)
            },Cesium.ScreenSpaceEventType.RIGHT_CLICK)

            /**
             * 创建开始节点
             */
            function createSatrtPointEntity() {
                that.viewer.entities.add({
                    position: positions[0],
                    type: "MeasureDistanceVertex",
                    point: {
                        color: Cesium.Color.RED,
                        pixelSize: 6,
                    },
                });
            }

            //创建面节点
            function  createVertex() {
                that.viewer.entities.add({
                    position: positions[positions.length - 1],
                    type: "MeasureDistanceVertex",
                    point: {
                        color: Cesium.Color.FUCHSIA,
                        pixelSize: 6,
                    },
                });
            }

            /**
             * 创建结束节点
             */
            function createEndPointEntity() {
                that.viewer.entities.add({
                    position: polygonPositions[ polygonPositions.length - 1 ],
                    type: "MeasureDistanceVertex",
                    point: {
                        color: Cesium.Color.BLUE,
                        pixelSize: 6,
                    },
                });
            }

            /**
             * 创建面实体
             */
            function createPolygonEntity() {
                that.viewer.entities.add({
                    name: "面几何对象",
                    polygon: {
                        hierarchy: new Cesium.CallbackProperty(e => {
                            return new Cesium.PolygonHierarchy(polygonPositions);
                            //使用最新1.72的时候 必须返回PolygonHierarchy类型 Cannot read property 'length' of undefined
                            //低版本好像都可以
                        }, false),
                        material: Cesium.Color.WHITE.withAlpha(0.6),
                        classificationType:Cesium.ClassificationType.BOTH, //这个显示面贴地很重要，具体解释可以查看官网
                    },
                    polyline: {
                        positions: new Cesium.CallbackProperty(e => {
                            return polygonPositions.concat(polygonPositions);
                        }, false),
                        width: 1,
                        material: new Cesium.PolylineDashMaterialProperty({
                            color: Cesium.Color.YELLOW,
                        }),
                        depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
                            color: Cesium.Color.YELLOW,
                        }),
                        clampToGround: true,//贴地画线
                    }
                })
            }

            //处理鼠标移动
            function  handleMoveEvent(position) {
                if (positions.length < 1) return;
                polygonPositions = positions.concat(position);

            }

        },
        /**
         * 
         * 清除事件
         * 
         */
        removeInputAction(key) {
            key == 7 ? this.index = -1 : ''
            this.dIndex = key;
            this.removeAll()
            if(this.handler){
                this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
                this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            }
        },
        /**
         * 移除球体上所有事物
         */
        removeAll() {
            this.viewer.entities.removeAll();
            if(this.handler){
                this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
                this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            }
        }

    }
}

</script>
<style scoped lang="scss">
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
.hello {
  height: 100%;
  #cesiumContainer {
    height: 100%;
  }
}
.drew{
    // width: 316px;
    height: 34px;
    border-radius: 5px;
    z-index: 4;
    position: absolute;
    left: 10px;
    top: 10px;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    background: rgba(255, 255, 255, 0.8);
    box-shadow: 0 0 0 2pxrgba 0, 0, 0, 0.1;
}
.text {
  font-size: 14px;
}
</style>